package org.brisling.sysman.queryService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.brisling.authorize.shiro.ShiroSecurityService;
import org.brisling.base.domain.ListDomain;
import org.brisling.base.domain.inf.BaseTreeNodeInf;
import org.brisling.base.service.AbstractBaseQueryService;
import org.brisling.common.ConstSysParam;
import org.brisling.common.SysConfig;
import org.brisling.common.exception.DangerousOperatorException;
import org.brisling.sysman.domain.UserPassword;
import org.brisling.sysman.domain.Users;
import org.brisling.sysman.domain.VODeptUser;
import org.brisling.sysman.domain.VOJobUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
@RequestMapping("/user/query")
public class QueryUserService extends AbstractBaseQueryService<Users>{
	
	
	@Autowired
	private QueryDictionaryService dicService;
	
	@Autowired
	private ShiroSecurityService shiroSecurityService;
	
	public QueryUserService(){
		this.moduleName = ConstSysParam.MODULE_USER;
		this.subSystem = ConstSysParam.SUBSYSTEM_SYSMAN;
		this.tableName = ConstSysParam.VIEW_PREFIX+this.moduleName;
		this.clazz = Users.class;
		
		typeMap = this.getTypeMap(clazz);
		
		
		orderMap.put("sortedid","asc");			
		
	}
	
	@PersistenceContext(unitName=ConstSysParam.SUBSYSTEM_SYSMAN)
	@Autowired
	protected void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;		
	}
	
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return this.getBizMainPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return this.getBizEditPage();
	}
	
	@RequestMapping("/getListDomain.action")
	public ListDomain<Users> getListDomain(@RequestBody(required=false) String body){	
		
		return super.getListDomainByConditionAndOrder(body, typeMap, orderMap,true);
	}
	
	/**
	 * 按照部门id查询所有人员信息
	 * @param page
	 * @param rows
	 * @param deptid	部门id值
	 * @param sort
	 * @param username	用户名
	 * @return
	 */
	@RequestMapping("/getListDomainByDeptid.action")
	public ListDomain<Users> getListDomainByDeptid(@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="rows",required=false) Integer rows,
			@RequestParam(value="deptid",required=false) Integer deptid,
			@RequestParam(value="sort",required=false) String sort,
			@RequestParam(value="username",required=false) String username){		
		String sql=null;
		String whereCorse=null;
		if(deptid==null&&username==null){
			ListDomain<Users> listDomain = new ListDomain<Users>();
			listDomain.setTotal(0l);
			listDomain.setRows(new ArrayList<Users>());
			return listDomain;
		}else if(deptid==null&&username!=null){
			sql = dicService.getSqlByBizcode("user_jobrole_list");
			whereCorse=String.format(("where name= '%1$s'"),username);
			sql = String.format(sql, whereCorse);
		}else if(deptid!=null&&username==null){
			sql = dicService.getSqlByBizcode("user_jobrole_list");
			whereCorse=String.format(("where deptid = %1$d"),deptid);
			sql = String.format(sql, whereCorse);	
		}else{
			sql = dicService.getSqlByBizcode("user_jobrole_list");
			whereCorse=String.format(("where deptid = %1$d and name= %2$s"),deptid,username);
			sql = String.format(sql, whereCorse);
		}
		
		return super.getPagedListDomain(page,rows,sql);
	}
	
	
	/**
	 * 获取管理人员数据集合
	 * @param page
	 * @param rows
	 * @param deptid
	 * @param sort
	 * @return
	 */
	@RequestMapping("/getManagerList.action")
	public List<VOJobUser> getManagerList(
			@RequestParam(value="deptid",required=false) Integer deptid){		
		
		
		String sql = dicService.getSqlByBizcode("user_jobrole_list");
		
		List<VOJobUser> lists = null;
		
		if(sql !=null && sql.trim().length()>0){
			
			String whereCorse="";
			if(deptid!=null){
				whereCorse=String.format(("where deptid = %1$d and jobcode <=40"),deptid);				
			}else{
				whereCorse="where jobcode <=40";				
			}
			
			sql = String.format(sql, whereCorse);
			
			try {
				lists= super.getClassedAllList(sql, VOJobUser.class);
			} catch (DangerousOperatorException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return lists;
	}
	
	/**
	 * 初始化加载管理用户数据集合
	 */
	@PostConstruct
	public void initialize(){
		Map<Long,Map<Long,List<VOJobUser>>> maps= SysConfig.getManageUserMap();
		if(maps==null || maps.isEmpty()){
			Map<Long,Map<Long,List<VOJobUser>>> paramMap = this.initMaps(this.getManagerList(null));
			if(paramMap!=null)
				SysConfig.setManageUserMap(paramMap);
		}
	}
	
	/**
	 * 刷新管理用户缓存信息
	 */
	@RequestMapping("/reloadCache.action")
	public String reloadCache(){
		SysConfig.setManageUserMap(null);
		this.initialize();
		return "200";
	}
	/**
	 * 封装管理用户集合，按照岗位、科室、人员三级进行封装
	 * @param lists
	 * @return
	 */
	private Map<Long,Map<Long,List<VOJobUser>>> initMaps(List<VOJobUser> lists){
		
		Map<Long,Map<Long,List<VOJobUser>>> umap = new HashMap<Long,Map<Long,List<VOJobUser>>>();
		
		if(lists!=null && lists.size()>0){
			for(VOJobUser u:lists){
				Long user_job_code = u.getJobcode();
				
				//判断map中是否存在当前岗位数据集合
				Map<Long,List<VOJobUser>> jobMap= null;
				if(umap.containsKey(user_job_code)){
					jobMap = umap.get(user_job_code);
				}else{
					jobMap = new HashMap<Long,List<VOJobUser>>();
				}
				
				//判断当前岗位数据集合中是否存在部门角色集合
				List<VOJobUser> deptjoblist = null;
				Long user_dept = u.getDeptid();
				if(jobMap.containsKey(user_dept)){
					deptjoblist = jobMap.get(user_dept);
				}else{
					deptjoblist = new ArrayList<VOJobUser>();
				}
				
				//将用户压入list
				deptjoblist.add(u);
				
				jobMap.put(user_dept, deptjoblist);
				
				
				umap.put(user_job_code, jobMap);
			}
		}
		
		return umap;
	}
	
	
	@RequestMapping("/getList.action")
	public List<Users> getList(@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="rows",required=false) Integer rows,
			@RequestParam(value="deptid",required=false) Integer deptid,
			@RequestParam(value="sort",required=false) String sort){		
		
		StringBuilder sb = new StringBuilder();
		String sql = "";
		if(deptid!=null){
			String whereCorse=String.format(sb.append("\"deptid\" = %1$d").toString(),deptid);
			sql = String.format(this.TW_SQL, this.tableName,whereCorse);
		}else{
			sql = String.format(this.T_SQL, this.tableName);
		}
		
		return super.getPagedList(page,rows,sql);
	}
	
	@RequestMapping("/getAllDeptUser.action")
	public List<VODeptUser> getAllDeptUser(){		
		
		
		String sql = String.format("select id,u.deptid,u.name,u.name as text,'u' as type,'glyphicon glyphicon-user' as icon from %1$s u order by u.sortedid",this.tableName);
		
		List<VODeptUser> retLists = null;
		try {
			retLists =super.getClassedAllList(sql, VODeptUser.class);
		} catch (DangerousOperatorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return retLists;
	}
	
	/**
	 * 查找指定部门节点下人员，并按照树结构组合于该节点下
	 * @param Long deptid
	 * @return
	 */
	@RequestMapping("/getConbinList.action")
	public List<BaseTreeNodeInf> getConbinList(@RequestParam(value="deptid",required=false) Long deptid){
		
		
		List<BaseTreeNodeInf> nodeList = new ArrayList<BaseTreeNodeInf>();
		
//		List<Users> list= this.getListByIdentify("sup_type", deptid.toString());
		
		String userid = shiroSecurityService.getCurrentUserIdentify();
		
		if(deptid!=null){
			List<Users> list = null;
			
			String superUserIdentify=SysConfig.getConfig(ConstSysParam.SUPER_USER_IDENTIFY);
			if (superUserIdentify.compareTo(userid)!=0){
			
				if(!isManageJob(userid)){
					//一般职员
					list =this.getListByIdentify("id", userid);
				}
			}else{
				//管理岗人员
				
				list =this.getListByIdentify("deptid", deptid.toString());
//				String sql = "select * from " + this.tableName + " where deptid in (%1$s)";
//				String deptids = this.getJobDeptids(userid);
//				if(deptids!=null){
//					sql = String.format(sql, deptids);
//					list = this.getAllList(sql);
//				}				
			}
			if(list!=null && list.size()>0){
				nodeList.addAll(list);
			}
		}		
		return nodeList;		
	}
	
	/**
	 * 根据用户id查找用户信息
	 * @param id	用户id
	 * @return 用户信息记录 
	 */
	@RequestMapping("/getOne.action")
	public Users getOne(@RequestParam(value="id",required=false) Long id){
		
		Users u = null ;
		if(id!=null){
			//查缓存
			u = SysConfig.getUsr(id.toString());

			//查后台数据
			if( null == u ){
				u = super.getOneByIdentify("id", id.toString());
				
				SysConfig.setUsr(u);
			}
		}
		return u;
	}
	
	/**
	 * 根据用户唯一编码查找用户信息
	 * @param identify	用户唯一编码
	 * @return 用户信息记录
	 */
	@RequestMapping("/getOneByIdentify.action")
	public Users getOneByIdentify(@RequestParam(value="identify",required=false) String identify){	
		return super.getOneByIdentify(identify);
	}
	
	/**
	 * 根据部门id查找用户集合
	 * @param page	页码
	 * @param rows	行数
	 * @param deptid	部门编码
	 * @return	用户数据集
	 */
	@RequestMapping("/getUserByDeptid.action")
	public ListDomain<Users> getUsersByDept(@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="rows",required=false) Integer rows,
			@RequestParam(value="deptid",required=false) Long deptid){
		
		String sql = " SELECT u.* FROM %1$s u LEFT JOIN %2$s d ON u.deptid=d.deptid AND d.deptid=%3$d" ;
		sql= String.format(sql, ConstSysParam.VIEW_USER, ConstSysParam.VIEW_PREFIX+ConstSysParam.MODULE_DEPARTMENT,deptid);		
		
		return super.getPagedListDomain(page, rows, sql);
	}
	
	/**
	 * 获取用户密码
	 * @param yhid
	 * @return
	 */
	@RequestMapping("/getUserPassword.action")
	public UserPassword getUserPassword(@RequestParam(value="yhid",required=false)String yhid){
		
		String sql = "select * from %1$s where yhdm = '%2$s'";
		sql = String.format(sql, "V_MH_XTYH",yhid);
		Query qry = entityManager.createNativeQuery(sql); 
		return (UserPassword) super.reflectObjectMap(UserPassword.class, super.getSingalQueryResult(qry), null);
	}
	
	
	
}
